package com.crm.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.crm.dao.CustomerDAO;
import com.crm.po.Customer;
import com.crm.util.DateEx;
import com.crm.util.ExcelEx;
import com.crm.util.RequestEx;
import com.crm.util.StringEx;
import com.crm.vo.Excel;

public class CustomerService {
	
	private static Logger logger = Logger.getLogger(CustomerService.class);
	
	public Map<String, Object> getCustomers(HttpServletRequest request){
		StringBuffer Hql = new StringBuffer(" from Customer t where 1=1 ");
		int page = Integer.parseInt(request.getParameter("page"));//当前第几页
		int rows = Integer.parseInt(request.getParameter("rows"));//每页显示几行
		
		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String name = RequestEx.getStringTrim(request.getParameter("name"));
		String linkman = RequestEx.getStringTrim(request.getParameter("linkman"));
		String product = RequestEx.getStringTrim(request.getParameter("product"));
		String fromDate = RequestEx.getStringTrim(request.getParameter("fromDate"));
		String toDate = RequestEx.getStringTrim(request.getParameter("toDate"));
		
		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.cGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(name != null && name.trim().length() > 0){
			Hql.append(" and t.name like '%");
			Hql.append(name);
			Hql.append("%' ");
		}
		if(linkman != null && linkman.trim().length() > 0){
			Hql.append(" and t.linkman like '%");
			Hql.append(linkman);
			Hql.append("%' ");
		}
		if(product != null && product.trim().length() > 0){
			Hql.append(" and t.product like '%");
			Hql.append(product);
			Hql.append("%' ");
		}
		if(fromDate != null && fromDate.trim().length() > 0){
			long tempFromDate = Long.parseLong(fromDate.replaceAll("-", "") + "000000");
			Hql.append(" and t.creattime >= ");
			Hql.append(tempFromDate);
		}
		if(toDate != null && toDate.trim().length() > 0){
			long tempToDate = Long.parseLong(toDate.replaceAll("-", "") + "235959");
			Hql.append(" and t.creattime <= ");
			Hql.append(tempToDate);
		}
		
		CustomerDAO dao = new CustomerDAO();
		String countHql = "select count(t.cid) " + Hql.toString();
		int count = dao.getCount(countHql);
		Hql.append(" order by t.creattime desc ");
	    List<Customer> list = dao.customerListPage(Hql.toString(), (page-1) * rows, rows);
	    
	    Map<String, Object> map = new HashMap<String, Object>();
	    map.put("count", count);
	    map.put("rows", list);
	    return map;
	} 
	
	public int getCustomerCountByTreeid(String treeid, String islive){
		StringBuffer Hql = new StringBuffer(" from Customer t where 1=1 ");

		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.cGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		
		CustomerDAO dao = new CustomerDAO();
		String countHql = "select count(t.cid) " + Hql.toString();
		int count = dao.getCount(countHql);
	    
	    return count;
	} 
	
	public boolean saveOrUpdateCustomer(HttpServletRequest request){
		try{
			String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
			
			String cid = RequestEx.getStringTrim(request.getParameter("cid"));
			String name = RequestEx.getStringTrim(request.getParameter("name"));
			String linkman = RequestEx.getStringTrim(request.getParameter("linkman"));
			String tel = RequestEx.getStringTrim(request.getParameter("tel"));
			String phone = RequestEx.getStringTrim(request.getParameter("phone"));
			String email = RequestEx.getStringTrim(request.getParameter("email"));
			String address = RequestEx.getStringTrim(request.getParameter("address"));
			String product = RequestEx.getStringTrim(request.getParameter("product"));
			String spec = RequestEx.getStringTrim(request.getParameter("spec"));
			Double price = RequestEx.getDouble(request.getParameter("price"));
			Integer sort = RequestEx.getInteger(request.getParameter("sort"));
			String remark = RequestEx.getStringTrim(request.getParameter("remark"));
			
			CustomerDAO dao = new CustomerDAO();
			Customer cus = null;
			if(cid != null && cid.trim().length() > 0){
				cus = dao.findById(cid);
			}else{				
				cus = new Customer();
				cus.setCreattime(DateEx.getCurDatetimeAsLong());
				cus.setCreater(RequestEx.getCurUser(request).getUsername());
			}
			
			cus.setcGroup(treeid);
			cus.setName(name);
			cus.setLinkman(linkman);
			cus.setTel(tel);
			cus.setPhone(phone);
			cus.setEmail(email);
			cus.setAddress(address);
			cus.setProduct(product);
			cus.setSpec(spec);
			cus.setPrice(price);
			cus.setSort(sort);
			cus.setRemark(remark);
			cus.setIslive("Y");
			cus.setUpdatetime(DateEx.getCurDatetimeAsLong());
			cus.setUpdater(RequestEx.getCurUser(request).getUsername());
						
			dao.saveOrUpdate(cus);
		}catch(Exception e){
			logger.error("save or update customer fail:", e);
			return false;
		}
	    return true;
	}
	
	public boolean deleteCustomers(HttpServletRequest request){
		int result = 0;
		try{
			String cids = RequestEx.getStringTrim(request.getParameter("cids"));
			if(cids.length() > 0){
				String hql = "UPDATE Customer T SET T.islive = 'N' WHERE T.cid IN (" + cids + ")";
				CustomerDAO dao = new CustomerDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("delete customer fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean recoverCustomers(HttpServletRequest request){
		int result = 0;
		try{
			String cids = RequestEx.getStringTrim(request.getParameter("cids"));
			if(cids.length() > 0){
				String hql = "UPDATE Customer T SET T.islive = 'Y' WHERE T.cid IN (" + cids + ")";
				CustomerDAO dao = new CustomerDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("recover customer fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public boolean reallyDeleteCustomers(HttpServletRequest request){
		int result = 0;
		try{
			String cids = RequestEx.getStringTrim(request.getParameter("cids"));
			if(cids.length() > 0){
				String hql = "DELETE FROM Customer T WHERE T.cid IN (" + cids + ")";
				CustomerDAO dao = new CustomerDAO();
				result = dao.executeHql(hql);
			}			
		}catch(Exception e){
			logger.error("really delete customer fail:", e);
			return false;
		}
	    return result > 0 ? true: false;
	}
	
	public void exportCustomers(HttpServletRequest request, HttpServletResponse response){
		StringBuffer Hql = new StringBuffer(" from Customer t where 1=1 ");
		
		String treeid = RequestEx.getStringTrim(request.getParameter("treeid"));
		String islive = RequestEx.getStringTrim(request.getParameter("islive"));
		String cids = RequestEx.getStringTrim(request.getParameter("cids"));
		String name = RequestEx.getStringTrim(request.getParameter("name"));
		String linkman = RequestEx.getStringTrim(request.getParameter("linkman"));
		String product = RequestEx.getStringTrim(request.getParameter("product"));
		String fromDate = RequestEx.getStringTrim(request.getParameter("fromDate"));
		String toDate = RequestEx.getStringTrim(request.getParameter("toDate"));
		
		if(treeid != null && treeid.trim().length() > 0){
			Hql.append(" and t.cGroup = '");
			Hql.append(treeid);
			Hql.append("' ");
		}
		if(islive != null && islive.trim().length() > 0){
			Hql.append(" and t.islive = '");
			Hql.append(islive);
			Hql.append("' ");
		}
		if(cids != null && cids.trim().length() > 0){
			Hql.append(" and t.cid in (");
			Hql.append(cids);
			Hql.append(") ");
		}
		if(name != null && name.trim().length() > 0){
			Hql.append(" and t.name like '%");
			Hql.append(name);
			Hql.append("%' ");
		}
		if(linkman != null && linkman.trim().length() > 0){
			Hql.append(" and t.linkman like '%");
			Hql.append(linkman);
			Hql.append("%' ");
		}
		if(product != null && product.trim().length() > 0){
			Hql.append(" and t.product like '%");
			Hql.append(product);
			Hql.append("%' ");
		}
		if(fromDate != null && fromDate.trim().length() > 0){
			long tempFromDate = Long.parseLong(fromDate.replaceAll("-", "") + "000000");
			Hql.append(" and t.creattime >= ");
			Hql.append(tempFromDate);
		}
		if(toDate != null && toDate.trim().length() > 0){
			long tempToDate = Long.parseLong(toDate.replaceAll("-", "") + "235959");
			Hql.append(" and t.creattime <= ");
			Hql.append(tempToDate);
		}
		
		CustomerDAO dao = new CustomerDAO();
		Hql.append(" order by t.sort ");
	    List<Customer> list = dao.customerList(Hql.toString());
	    
	    String[][] grids = new String[list.size() + 1][12];
	    String[] titles = {"客户公司", "联系人", "固定电话 ", "移动电话 ", "电子邮箱", "地址", "产品", "规格", 
				   		   "价格", "备注", "创建时间", "修改时间"}; 
	    grids[0] = titles;
		for(int i = 0; i < list.size(); i ++){
			Customer cus = list.get(i);
			
			grids[i + 1][0] = StringEx.valueOf(cus.getName());
			grids[i + 1][1] = StringEx.valueOf(cus.getLinkman());
			grids[i + 1][2] = StringEx.valueOf(cus.getTel());
			grids[i + 1][3] = StringEx.valueOf(cus.getPhone());
			grids[i + 1][4] = StringEx.valueOf(cus.getEmail());
			grids[i + 1][5] = StringEx.valueOf(cus.getAddress());
			grids[i + 1][6] = StringEx.valueOf(cus.getProduct());
			grids[i + 1][7] = StringEx.valueOf(cus.getSpec());
			grids[i + 1][8] = StringEx.valueOf(cus.getPrice());
			grids[i + 1][9] = StringEx.valueOf(cus.getRemark());
			grids[i + 1][10] = StringEx.valueOfLongDate(cus.getCreattime());
			grids[i + 1][11] = StringEx.valueOfLongDate(cus.getUpdatetime());
		}
	    ExcelEx.toExcel(request, response, new Excel("客户信息[导出时间" + DateEx.getCurDateTime() + "]", grids));

	} 
	
	
}
